using SqlQueryBuilder.Clauses;
using SqlQueryBuilder.Util;

namespace SqlQueryBuilder.Criterias
{
    /// <summary>
    /// Join Criteria
    /// </summary>
    public class Join : ICriteria
    {
        private readonly JoinType type;
        private readonly string table;
        private readonly IConditionalClause clause;
        private readonly string alias;

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Join"/> class.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="table">The table.</param>
        /// <param name="clause">The clause.</param>
        public Join(JoinType type, string table, IConditionalClause clause) : this(type, table, "", clause) { }

        /// <summary>
        /// Initializes a new instance of the <see cref="Join"/> class.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="table">The table.</param>
        /// <param name="alias">The alias.</param>
        /// <param name="clause">The clause.</param>
        public Join(JoinType type, string table, string alias, IConditionalClause clause)
        {
            this.type = type;
            this.alias = alias;
            this.clause = clause;
            this.table = table;
        }

        #endregion

        /// <summary>
        /// Builds the criteria.
        /// </summary>
        /// <returns></returns>
        public string BuildCriteria()
        {
            return clause == null ? 
                string.Empty : 
                string.Format("{0} {1} {2} ON {3} ", GetJoinType(), table, alias, clause.BuildConditionalClause());
        }

        /// <summary>
        /// Gets the type of the join.
        /// </summary>
        /// <returns></returns>
        private string GetJoinType()
        {
            switch (type)
            {
                case JoinType.InnerJoin: return "INNER JOIN";
                case JoinType.LeftJoin: return "LEFT JOIN";
                case JoinType.RightJoin: return "RIGHT JOIN";
                default : return "JOIN";
            }
        }
    }
}